#coding=utf-8
import time 
import os
import re

class CompareData:
    def __init__(self):

        self.dataset={}
        self.result = []
        self.dbroot = "/Users/haoyu/Documents/password_db/db"
        #self.dbroot = "/home/haoyu/db"
        self.starttime = time.time()
        self.debug = True
    
    def mysplit (self,string):
        quote = False
        retval = []
        current = ""
        for char in string:
            if char == '"':
                quote = not quote
            elif char == ',' and not quote:
                retval.append(current)
                current = ""
            else:
                current += char
        retval.append(current)
        return retval
          
    def get_key(self,username,passwd,email):
      key ="%s,%s" % (passwd,email)
      return key
    
    def has_cn(self,line):
        if re.findall('[\x80-\xff]',line):
            return True
        else:
            return False
    def valid_passwd(self,strpasswd):
      pattern = re.compile(r"[ A-Za-z0-9!@#$%^&*()+=_-]{8,}")
      pattern.match(strpasswd)
    
    def check_password(self,password):
      score = 1
      if len(password)<8 :
        return score
      if re.search('\d+',password):
        score +=1
      if re.search('[a-zA-Z]',password) : #and re.search('[A-Z]',password):
        score +=1
        
      if re.search('[^0-9^a-z^A-Z]',password):
        score +=1
      return score
      
    def load_data(self,filekey):
      
      if len(filekey)==0:
        return None
      
      filename = os.path.join(self.dbroot,"%s.txt" % filekey)
    
      starttime = time.time()
      dataset = {}
      c = 0
      func = getattr(self,"%s_parser" % filekey)  
      for row in open(filename,"r"):
        c +=1
        rs = func(row)
        #rs = self.renren_parser(row)
        if not rs:
          continue
        username,passwd,email = rs
        
        key = self.get_key(username, passwd, email)
        
        dataset[key] = 1

      print "load %s data over!count:%s,valid:%s" % (filekey,c,len(dataset))
      print "load %s data elapse time:%s" % (filekey,time.time() - starttime) 
      self.dataset = dataset
      dataset = None

    def duowan_parser(self,row):
      row = row.strip()   
      if not row:
          return None
      rs = map(lambda x:x.strip(),row.split())
      if len(rs)<2:
        return None
      
      #id = rs[0]
      username = rs[1]
      passwd = "".join(rs[2:])
      email = None
      if self.debug:
        print "duowan:%s,%s,%s"% (username,passwd,email )     
      return (username,passwd,email)
      
    def renren_parser(self,row):
      row = row.strip()   
      if not row:
          return None
      rs = map(lambda x:x.strip(),row.split())
      if len(rs)<2:
        return None
      
      email = rs[0]
      passwd = "".join(rs[1:])
      username = None
      if self.debug:
        print "renren:%s,%s,%s"% (username,passwd,email )     
      return (username,passwd,email)
        
    def sina_parser(self,row):
      row = row.strip()   
      if not row:
          return None
      rs = map(lambda x:x.strip(),row.split())
      if len(rs)<2:
        return None
      
      email = rs[0]
      passwd = "".join(rs[1:])
      username = None  
      if self.debug:
        print "sina:%s,%s,%s"% (username,passwd,email )        
      return (username,passwd,email)     

    def csdn_parser(self,row):
      row = row.strip()   
      if not row:
          return None
      rs = map(lambda x:x.strip(),row.split(" # "))
      username = rs[0]
      passwd = "".join(rs[1:len(rs)-1])
      email = rs[len(rs)-1] 
      if self.debug:
        print "csdn:%s,%s,%s"% (username,passwd,email)            
      return (username,passwd,email) 
    
    def tianya_parser(self,row):
      row = row.strip()   
      if not row:
          return None
      rs = map(lambda x:x.strip(),row.split())
      if len(rs)<2:
        return None
      if len(rs)<3:
        username = rs[0]
        passwd = rs[1]
        email = None
      else:
        username = rs[0]
        passwd = "".join(rs[1:len(rs)-1])
        email = rs[len(rs)-1] 
      if self.debug:
        print "tianya:%s,%s,%s"% (username,passwd,email )                
      return (username,passwd,email)      
                  
    def compare(self,filekey):
      c = 0
      ie = 0
      t2 = time.time()
      result = []
      func = getattr(self,"%s_parser" % filekey) 
      for row in open(os.path.join(self.dbroot,"%s.txt" % filekey)):            
        c += 1
        try:
            rs = func(row)
            if not rs:
              continue
            username,passwd,email = rs
            
            key = self.get_key(username, passwd, email)
            if self.dataset.has_key(key):
              result.append("%s\n" % (key))
           
        except Exception,ex:
          ie +=1
          if self.debug:
            print "error:%s" % ex
            print row
      
      self.result = list(set(result))
      result = None
      print "compare %s data over!count:%s,error:%s,repeat:%s" % (filekey,c,ie,len(self.result))
      print "compare %s data elapse time:%s" % (filekey,time.time() - t2)       
        
     
def sort_data(fkey):
  cdc = CompareData()
  cdc.debug = False
  
  cdc.load_data(fkey)
  dataset = cdc.dataset
  sortedkeys = sorted(dataset)
  
  f = open("%s_sort.txt" % (fkey),"w")
  for email in sortedkeys:
    #print email,dataset[email]
    username,passwd  = dataset[email]
    f.write("%s,%s,%s\n" % (username,passwd,email))
  f.close()

def check_password(key1):
    
    cdc = CompareData()
    cdc.debug = False
    cdc.load_data(key1)
    dataset = cdc.dataset
    c3 = 0
    c4 = 0
    c4set = []
    
    for email in dataset:
      username ,password = dataset[email]
      score = cdc.check_password(password)
      
      if score ==4:
        c4 +=1
        c4set.append("%s,%s\n" % (username,email,password))
      if score == 3:
        c3 +=1
    
    print "c3:%s" % c3
    print "c4:%s" % c4
    open("strong_pwd_%s.log" % key1,"w").writelines(c4set)
     
def c2c(key1,key2s):
    
    cdc = CompareData()
    cdc.debug = False
    #cdc.get_key = lambda u,p,e: "%s,%s,%s"%(u,p,e)
    cdc.load_data(key1)
    
    for key2 in key2s:
      if not key2:
        continue
      cdc.compare(key2)
      cdc.result=[]
      #open("%s_%s.log" % (key1,key2),"w").writelines(cdc.result)
             
if __name__ == "__main__":
  #c2c("sina",["renren","csdn","tianya"])
  #c2c("renren",["sina",])
  c2c("csdn",["renren",])

      
